package pl.edu.pw.ee.buildcity.ui.web.jsf.beans;

import org.apache.log4j.Logger;
import pl.edu.pw.ee.buildcity.entities.BuildDefinition;
import pl.edu.pw.ee.buildcity.scheduler.api.BuildCityScheduler;
import pl.edu.pw.ee.buildcity.services.BuildDefinitionService;

import javax.annotation.PostConstruct;
import javax.faces.model.ListDataModel;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author mgrzechocinski
 * @since 2009-11-08
 */
public class DashboardJSFBean {

	private static final Logger log = Logger.getLogger(DashboardJSFBean.class);

	private final ListDataModel allBuildsDefinitions = new ListDataModel();

	private BuildDefinitionService buildDefinitionService;
	private BuildDefinition chosenBuildDefinition;
	private BuildCityScheduler buildCityScheduler;

	@SuppressWarnings("unused")
	@PostConstruct
	private void initBuildDefinitions() {
		List<BuildDefinition> registeredBuildDefinitions = buildDefinitionService.getAll();
		Collections.sort(registeredBuildDefinitions, new BuildDefinitionNameComparator());
		allBuildsDefinitions.setWrappedData(registeredBuildDefinitions);
	}

	public void fireBuild() {
		BuildDefinition bDef = (BuildDefinition) allBuildsDefinitions.getRowData();
		buildCityScheduler.fireNow(bDef.getName());
	}

	public ListDataModel getAllBuildsDefinitions() {
		return allBuildsDefinitions;
	}

	public String showBuildDefinitionDetails() {
		chosenBuildDefinition = (BuildDefinition) allBuildsDefinitions.getRowData();
		return "toBuildDefinitionDetails";
	}

	public String showLastBuildActivityDetails() {
		chosenBuildDefinition = (BuildDefinition) allBuildsDefinitions.getRowData();
		return "toLastBuildActivityDetails";
	}

	public BuildDefinition getChosenBuildDefinition() {
		return chosenBuildDefinition;
	}

	public void setBuildDefinitionService(BuildDefinitionService buildDefinitionService) {
		this.buildDefinitionService = buildDefinitionService;
	}

	public void setBuildCityScheduler(BuildCityScheduler buildCityScheduler) {
		this.buildCityScheduler = buildCityScheduler;
	}

	private class BuildDefinitionNameComparator implements Comparator<BuildDefinition> {
		@Override
		public int compare(BuildDefinition o1, BuildDefinition o2) {
			return String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName());
		}
	}
}
